import Pay from '@/utils/pay.js' // 支付对象
import baseUrl from '@/utils/baseUrl.js' // api接口地址
export default {
  data() {
    return {
      sweixin: null,
      price: 888,
      type: 'accessory', //  入口标识 maintenance:维保 maintenanceorder：维保订单下单支付
      orderNo: '', //  订单号id
      payTypess: [
        {
          name: '微信支付',
          value: '1',
          icon: 'iconweixin',
          color: '#09BB07'
        },
        {
          name: '余额支付',
          value: '2',
          icon: 'iconyue',
          color: '#FBB000'
        }
      ],
      // 支付方式列表
      payTypes: [
        {
          name: '支付宝支付',
          value: '0',
          icon: 'iconzhifubao',
          color: '#02A9F1'
        },
        {
          name: '微信支付',
          value: '1',
          icon: 'iconweixin',
          color: '#09BB07'
        },
        {
          name: '余额支付',
          value: '2',
          icon: 'iconyue',
          color: '#FBB000'
        }
      ],
      payPlatformType: 0, // 支付平台值 0原生支付平台  20云商通支付平台
      payType: 0, //支付类型  60小程序 20支付宝

      // 支付环境
      // #ifdef H5
      payPlatformDetailType: 1,
      // #endif

      // #ifdef APP-PLUS
      payPlatformDetailType: 3,
      // #endif

      formDom: '', // 表单标签元素

      mShow6: false,
      mShowye: false,
      isSetPayPsd: false,
      paypsd: false, //支付密码
      payPassword: '', //支付密码
      couponId: '', //优惠券id
      title: '',
      isWxx: false, //是否在微信打开
      isDisabledSubmitBtn: true, //按钮是否禁用
      machineId: '', // 机器id
      info: null,
      isBindPhone: false, //是否显示绑定手机号
      phoneValue: '', //验证码值
      mobile: '',
      aweixin: null,
      jump: '',//跳转逻辑（back为返回上一页）
    }
  },

  computed: {
    serviceNumber(){
      return this.$store.state.serviceNumber
    }
  },

  onLoad(e) {
    console.log(e)
    //#ifdef APP-PLUS
    //app判断是否有安装微信
    this.getPlus()
    //获取登录鉴权
    this.authorize()
    //#endif
    //福利购标题
    this.title = e.title
    //福利购id
    // this.couponId = e.id

    //订单号
    this.orderNo = e.orderNo
    //价格
    this.price = e.price
    //上个页面传过来的支付模块    type=maintenance||maintenanceorder维保    buyDiscountsOrder福利购  selfServiceCarWashCoupon自助洗车 selfHelpWashCar自动洗车 否则就是购车
    this.type = e.type ? e.type : '',
    //洗车机ID
    this.machineId = e.machineId ? e.machineId : ''
    // console.log(this.type)
    // 获取我的收益
    this.getUserMoneyInfo()
    this.mobile = uni.getStorageSync('Ztc_C_USER_INFO').mobile
    this.jump = e.jump
  },
  onShow() {
    //是否设置支付密码
    this.IsExistPayPwd()
    //#ifdef MP-WEIXIN
    this.isWxx = true
    this.payPlatformType = 1
    this.payType = 1
    this.payPlatformDetailType = 4
    //#endif
    //回调
    //#ifdef APP-PLUS
    if (this.type === 'selfServiceCarWashCoupon') {
      this.checkOrderCardPaid(res => {
        console.log(res.data.isSuccess, '支付')
        if (res.data.isSuccess) {
          console.log('支付成功')
          this.goSuccessPage()
        } else {
          console.log('支付失败')
        }
      })
    }
    //#endif
  },
  methods: {
    //获取登录鉴权
    authorize(){
      plus.oauth.getServices(function(services){
        console.log(services)
      		for(var i in services){
      			auths[service.id]=service
      		}
      		aweixin = auths['weixin']
      	}, function(e){
      		plus.nativeUI.alert('获取登录鉴权服务列表失败：'+JSON.stringify(e))
      	} )
    },
    getPlus() {
      //获取当前显示的webview
      var pages = getCurrentPages()
      var page = pages[pages.length - 1]
      var currentWebview = page.$getAppWebview()
      var shares = null
      let that = this
      var pusher = plus.share.getServices(function(s) {
        shares = {}
        for (var i in s) {
          var t = s[i]
          shares[t.id] = t
        }
        that.sweixin = shares['weixin']
      }, function(e) {
        console.log('获取分享服务列表失败：' + e.message)
      })
      //放入当前的webview
      currentWebview.append(pusher)
    },
    // 支付方法集合
    async payApp(orderInfo) {
      console.log(orderInfo)
      switch (this.payType) {
      // 支付宝
      case 0:
        let payInfo = orderInfo.payInfo
        uni.navigateTo({
          url: '/pages_commodity/wxPay/alipay?url=' + payInfo
        })
        break
        // 微信
      case 1:
        try {
          //#ifdef MP-WEIXIN
          let infoObj = JSON.parse(orderInfo.payInfo)
          uni.requestPayment({
            'timeStamp': infoObj.timeStamp,
            'nonceStr': infoObj.nonceStr,
            'package': infoObj.package,
            'paySign': infoObj.paySign,
            'signType': infoObj.signType,
            success: res => {
              this.goSuccessPage()
              console.log('res', res)
            },
            fail: err => {
              console.log('err', err)
            }
          })
          //#endif
          //#ifndef  MP-WEIXIN
          let type
          if (baseUrl === 'https://testapi.yzsheng.com') {
            type = 2
          } else if (baseUrl === 'https://lineapi.yzsheng.com') {
            type = 0
          }
          if (this.sweixin){
            this.sweixin.launchMiniProgram({ // 微信小程序的ID
              id: 'gh_fe19d042f1b9',
              type: type,
              path: '/pages_commodity/wxPay/wxPay?appOrderJson='+ JSON.stringify(orderInfo)
            })
          }
          //#endif
        } catch (err) {
          console.log('app微信支付失败', err)
          uni.showToast({
            title: '支付失败已取消支付',
            icon: 'none'
          })
        }
        break
      }
    },
    //获取验证码
    async onBindPhone(e) {
      try {
        let data = {
          'phone': uni.getStorageSync('Ztc_C_USER_INFO').mobile,
          'CurrentUserId': uni.getStorageSync('Ztc_C_USER_INFO').id
        }
        const res = await this.$api.fundModule.sendVerificationCode(data)
        this.isBindPhone = true
      } catch (e) {
        //TODO handle the exception
      }
    },
    //绑定手机号
    async onBindYz(e) {
      try {
        let data = {
          'phone': this.mobile,
          'verificationCode': this.phoneValue,
          'CurrentUserId': uni.getStorageSync('Ztc_C_USER_INFO').id
        }
        const res = await this.$api.fundModule.bindPhone(data)
        console.log(res)
        this.isBindPhone = false
        this.getSubmit()
      } catch (e) {
        //TODO handle the exception
      }
    },
    //是否绑定手机号
    async getCertificationProgress() {
      try {
        let data = {
          'type': 0
        }
        const res = await this.$api.fundModule.getCertificationProgress(data)
        if (!res.data.bindPhone && this.payType !== 2) {
          this.onBindPhone()
          return
        } else {
          this.getSubmit()
        }
      } catch (e) {
        //TODO handle the exception
      }
    },
    //洗车订单是否成功
    async checkOrderCardPaid(call) {
      try {
        let data = {
          'id': this.orderNo
        }
        const res = await this.$api.selfServiceCarWash.CheckOrderCardPaid(data)
        call(res)
      } catch (e) {
        //TODO handle the exception
      }
    },
    //是否设置支付密码
    async IsExistPayPwd() {
      try {
        const res = await this.$api.user.IsExistPayPwd()
        this.isSetPayPsd = res.data
      } catch (e) {
        console.log(e)
      }
    },

    // 单选监听
    radioChange(e) {
      this.payType = Number(e.target.value)
      // console.log(e.target.value, '123')
    },

    //获取优惠券id(福利购，支付成功之后调用)
    async getCouponIdByBuyDiscountsOrderId() {
      try {
        let data = {
          'buyDiscountsId': this.orderNo
        }
        const res = await this.$api.maintenanceIndex.getCouponIdByBuyDiscountsOrderId(data)
        this.couponId = res.data
        console.log(res)
        //#ifdef APP-PLUS
        uni.redirectTo({
          url: '/pages_commodity/myLoveCar/myLoveCar?type=100' + '&id=' + this.couponId +
						'&title=' + this.title
        })
        //#endif
      } catch (e) {
        //TODO handle the exception
      }
    },
    // 自助洗车优惠券购买成功
    selfServiceCarWashCouponSuccess() {
      this.$store.commit('setMachineId','')
      //#ifdef APP-PLUS || MP-WEIXIN
      if (this.machineId) {
        uni.redirectTo({
          url: `/pages_commodity/selfWash/existingOrder?id=${this.machineId}`
        })
      } else {
        uni.showToast({
          title: '支付成功',
          icon: 'success'
        })
        setTimeout(() => {
          uni.redirectTo({
            url: '/pages_commodity/selfWash/selfWash'
          })
        }, 1000)
      }
      //#endif
    },
    // 跳转到成功页面
    goSuccessPage() {
      if (this.type === 'buyDiscountsOrder') {
        this.getCouponIdByBuyDiscountsOrderId()
      } else if (this.type === 'selfServiceCarWashCoupon' || this.type === 'selfHelpWashCar') {
        this.selfServiceCarWashCouponSuccess()
      } else {
        this.goSuccess()
      }

    },
    //支付成功跳转(通用)
    goSuccess() {
      //#ifdef APP-PLUS || MP-WEIXIN
      uni.redirectTo({
        url: '/pages_commodity/paySuccessful/paySuccessful'
      })
      //#endif
    },
    //余额支付
    async ClientBalancePay() {
      let payModule = null
      if (this.type === 'maintenance' || this.type === 'maintenanceorder') {
        payModule = 3
      } else if (this.type === 'buyDiscountsOrder') {
        payModule = 4
      } else if (this.type === 'selfServiceCarWashCoupon') {
        payModule = 7
      } else if(this.type === 'selfHelpWashCar'){
        payModule = 8
      } else {
        payModule = 2
      }
      if (this.payPassword.length === 6) {
        let data = {
          id: this.orderNo,
          userInputPayPassword: this.payPassword,
          payModule: payModule //购车--2 维保--3 福利购--4
        }
        try {
          const res = await this.$api.common.ClientBalancePay(data)
          console.log('余额支付', res)
          if (res.code == '-4') {
            uni.showToast({
              title: res.parmeter || res.msg,
              icon: 'none'
            })
          } else if (res.code === 200) {
            uni.showToast({
              title: '支付成功！',
              icon: 'success'
            })
            if (this.type === 'selfServiceCarWashCoupon') {
              this.selfServiceCarWashCouponSuccess()
            }
          } else {
            uni.showToast({
              title: res.parmeter || res.msg,
              icon: 'none'
            })
          }
          this.paypsd = false

        } catch (err) {

        }
      } else {
        uni.showToast({
          title: '请输入正确的支付密码',
          icon: 'none'
        })
      }
    },

    // 自助洗车优惠券支付
    async selfServiceCarWashCoupon() {
      let _this=this

      let data = {
        orderId: this.orderNo,
        payModule: 7,
        // #ifdef H5
        returnUrl: encodeURI(window.location.origin + window.location.pathname +
					`#/pages_commodity/paySuccess/paySuccess?id=${this.orderNo}&type=${this.type}`)
        // #endif
      }
      try {
        //#ifdef MP-WEIXIN
        wx.login({
          success(code) {
            data.PayType=1
            data.Code=encodeURIComponent(code.code)
            _this.$api.selfServiceCarWash.selfServiceCarWash(data).then(res => {
              console.log(res)
              _this.payApp(res.data)
            })
          }
        })
        //#endif

        // #ifdef APP-PLUS
        //前端带上页面参数直接打开小程序
        uni.hideLoading()
        if (this.payType === 1) {
          this.payApp({orderId: data.orderId,payModule: data.payModule,token: uni.getStorageSync('token')})
        }else{
          data.PayType=2
          await this.$api.selfServiceCarWash.selfServiceCarWash(data).then(res => {
            this.payApp(res.data)
          })
        }
        // #endif

      } catch (err) {
        uni.hideLoading()
        uni.showToast({
          title: err,
          icon: 'none'
        })
        console.log('自助洗车会员支付接口错误', err)
      }
    },
    //支付处理
    getPayType(){
      if (this.type === 'selfServiceCarWashCoupon') {
			  this.selfServiceCarWashCoupon()
      }
    },
    //余额支付input值
    finish(e) {
      console.log(e)
      this.payPassword = e
    },
    getSubmit() {
      if (this.payType === 2) {
        if (this.isSetPayPsd) {
          this.paypsd = true
        } else {
          uni.showToast({
            title: '请先设置支付密码',
            icon: 'none'
          })
          setTimeout(() => {
            uni.navigateTo({
              url: '/pages_userModule/setPassword/setPsd'
            })
          }, 1200)
        }
      } else {
        let _this = this
        let payType = this.payType
        let platform = ''
        // #ifdef APP-PLUS
        if (payType === 0) {
          platform = 20 // 支付宝app支付(50)
          this.payPlatformType = 20
          this.payPlatformDetailType = platform
          this.getPayType()
        } else if (payType === 1) {
          uni.showLoading()
          let openid = uni.getStorageSync('wxData')
          platform = 60 // 微信app支付（55）
          this.payPlatformType = 20
          this.payPlatformDetailType = platform
          this.getPayType()

        }
        // #endif
        // #ifdef MP-WEIXIN
        if (payType === 1) {
          platform = 60 // 微信小程序支付
        } else if (payType === 2) {
          platform = 50 // 余额
        }
        this.payPlatformType = 20
        this.payPlatformDetailType = platform
        // #endif

        // #ifndef APP-PLUS
        this.getPayType()
        //#endif
      }
    },
    // 点击确认支付
    submit() {
      this.getSubmit()
    },

    //获取我的收益
    async getUserMoneyInfo() {
      try {
        const res = await this.$api.me.getUserMoneyInfo({})
        // console.log(res)
        this.info = res.data
      } catch (e) {
        console.log(e)
        plus.runtime.arguments = null
        plus.runtime.arguments = ''
      }
    },
    // 打电话
    call() {
      AddMobileContactData(this.$store.state.userInfoDetail.store.storeId)
      uni.makePhoneCall({
        phoneNumber: this.serviceNumber.number
      })
    },

    confirmHE() {},
    confirm() {},
    filterTel(tel) {
      let reg = /^(\d{3})\d*(\d{4})$/
      return tel.replace(reg, '$1****$2')
    },
    Onpwd(e) {
      this.phoneValue = e
    },
  }
}
